﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace HealthExaminationSys.Common
{
    /// <summary>
    /// 应用程序配置辅助类
    /// </summary>
    public class AppConfig
    {
        static Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        /// <summary>
        /// 通过ConnStr名称获取ConnectionStringSettings
        /// </summary>
        /// <param name="key">ConnStr名称</param>
        /// <returns>ConnectionStringSettings</returns>
        public static ConnectionStringSettings GetConnStrSetting(string key)
        {
            ConnectionStringSettings val = new ConnectionStringSettings();
            if (config.ConnectionStrings.ConnectionStrings[key] != null)
                val = config.ConnectionStrings.ConnectionStrings[key];
            return val;
        }
        /// <summary>
        /// 设置并保存数据库连接字符串和提供程序名称
        /// </summary>
        /// <param name="key">ConnStr名称</param>
        /// <param name="connStr">连接字符串</param>
        /// <param name="providerName">提供程序名称</param>
        public static void SetConnStrSetting(string key, string connStr, string providerName)
        {
            if (config.ConnectionStrings.ConnectionStrings[key] != null)
            {
                config.ConnectionStrings.ConnectionStrings[key].ConnectionString = connStr;
                config.ConnectionStrings.ConnectionStrings[key].ProviderName = providerName;
            }
            else
            {
                config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(key, connStr, providerName));
            }
            config.Save(ConfigurationSaveMode.Modified);
        }
        /// <summary>
        /// 获取应用程序设置的值（如果没有查到 key 对应的键值对，会添加此key对应的键值对并返回 null）
        /// </summary>
        /// <param name="key">应用程序设置的键</param>
        /// <returns>应用程序设置的值</returns>
        public static string GetValue(string key)
        {
            string strReturn = null;
            if (config.AppSettings.Settings[key] != null)
            {
                strReturn = config.AppSettings.Settings[key].Value;
            }
            else
            {
                config.AppSettings.Settings.Add(key, null);
            }
            return strReturn;
        }
        /// <summary>
        /// 设置应用程序设置的值（如果没有查到 <paramref name="key"/> 对应的键值对，会添加此<paramref name="key"/>对应的键值对并将 Value 设置为 <paramref name="value"/>）
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public static void SetValue(string key, string value)
        {
            if (config.AppSettings.Settings[key] != null)
            {
                config.AppSettings.Settings[key].Value = value;
            }
            else
            {
                config.AppSettings.Settings.Add(key, value);
            }
            config.Save(ConfigurationSaveMode.Modified);
        }
    }
}
